//
//  HMStatusListViewModel.m
//  HMWeiBoOC
//
//  Created by GD on 16/9/23.
//  Copyright © 2016年 geduo. All rights reserved.
//

#import "HMStatusListViewModel.h"
#import "HMNetworkTools.h"
#import "HMUserAccountViewModel.h"
#import <YYModel.h>
#import "HMStatusViewModel.h"//修改以后,该list直接拥有的是ViewModel模型,而不是以前的Status模型
#import <SDWebImage/SDWebImageManager.h>

//#import "HMUser.h"

//  封装首页微博数据网络请求 -> 首页的TableView
@implementation HMStatusListViewModel

-(instancetype)init{
    if (self = [super init]) {
        _statusList = [NSMutableArray array];
    }
    return self;
}



+(instancetype)shareManager{
    
    static HMStatusListViewModel *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [self new];
    });
    
    return instance;
}

//  封装首页微博数据网络请求 -> 首页的TableView
-(void)loadData:(BOOL)isPullup WithCallBack:(void (^)(BOOL, NSString*))callBack{
    
    NSString *accessToken= [HMUserAccountViewModel sharedViewModel].accessToken;
    
    int64_t maxId = 0;
    int64_t sinceId = 0;
    if (isPullup) {//上拉加载
        maxId = self.statusList.lastObject.status.id;
        
        if (maxId > 0) {
            maxId -= 1;
        }else{//下拉刷新
            sinceId = self.statusList.firstObject.status.id;
        }
    }
    __block NSString *message = @"";
    [[HMNetworkTools sharedTools] requestStatusesWithAccessToken:accessToken maxId:maxId sinceId:sinceId andCallBack:^(id result, NSError *error) {
        
        if (error) {
            NSLog(@"网络异常 %@",error);
            callBack(NO,message);
            return ;
        }
        
        NSArray *dictArray = result[@"statuses"];
        
//        NSLog(@"%@",dictArray);
        NSArray *statusArr = [NSArray yy_modelArrayWithClass:[HMStatus class] json:dictArray];
        
        
        dispatch_group_t group = dispatch_group_create();
        
        NSMutableArray *tempArr = [NSMutableArray array];
        for (HMStatus *status in statusArr) {
//            NSLog(@"%@",status.user.screen_name);
            HMStatusViewModel *statusViewModel = [[HMStatusViewModel alloc] initWithStatus:status];
            
            [tempArr addObject: statusViewModel];
            
            //单张图片
            if (status.pic_urls.count == 1) { //  原创微博配图等于1张,需要下载
                NSString *url = status.pic_urls.firstObject.thumbnail_pic;
                dispatch_group_enter(group);
                dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
                    [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:url] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                        NSLog(@"下载完成 1");
                        dispatch_group_leave(group);
                    }];
                });
            }
            
            if (status.retweeted_status.pic_urls.count == 1) { //  转发微博图片等于1张,需要下载
                NSString *url = status.retweeted_status.pic_urls.firstObject.thumbnail_pic;
                dispatch_group_enter(group);
                dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
                    [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:url] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                        NSLog(@"下载完成 2");
                        dispatch_group_leave(group);
                    }];
                });
            }
            
        }
        
        if (tempArr.count > 0) {
            message = [NSString stringWithFormat:@"%zd条新数据",tempArr.count];
        }
        
        
//        self.statusList = tempArr;
        if (isPullup) {   //  如果上拉加载需要把数据追加到原始数组后面
            [self.statusList addObjectsFromArray:tempArr];
        }else{//  下拉刷新
            [self.statusList insertObjects:tempArr atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, tempArr.count)]];
        }
        
        dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                NSLog(@"单张图片下载完成---");
                callBack(YES,message);//数据请求完成后  转模型后 回调
            });
        });
        
        
    }];
}

@end
